package com.algorithm.ch1.cjm.linkedlist;

import com.algorithm.ch1.cjm.linkedlist.model.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 请判断一个链表是否为回文链表。
 * <p>
 * 示例 1:
 * <p>
 * 输入: 1->2
 * 输出: false
 * 示例 2:
 * <p>
 * 输入: 1->2->2->1
 * 输出: true
 * 进阶：
 * 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题？
 */
public class IsPalindrome {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(-1);
        ListNode node2 = new ListNode(-2);
        ListNode node3 = new ListNode(-3);
        ListNode node4 = new ListNode(-3);
        ListNode node5 = new ListNode(-2);
        ListNode node6 = new ListNode(-1);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;

        System.out.println(isPalindrome1(node1));
    }

    /**
     * 第一版
     * T(n) = n + n/2
     * f(n)= n
     * @param head
     * @return
     */
    public static boolean isPalindrome(ListNode head) {

        if (head == null || head.next == null) {
            return true;
        }
        if (head.val == head.next.val && head.next.next == null) {
            return true;
        }

        ListNode next = head;

        List<Integer> lists = new ArrayList<>();
        while (next != null){

            lists.add(next.val);

            next = next.next;
        }

        int start = 0;
        int end = lists.size() - 1;

        while (start < end){

            if(lists.get(start).intValue() != lists.get(end).intValue()){
                return false;
            }

            start++;
            end--;
        }

        return true;
    }

    /**
     * leetcode 最优解
     * @param head
     * @return
     */
    public static boolean isPalindrome1(ListNode head){

        if (head == null || head.next == null) {
            return true;
        }
        if (head.val == head.next.val && head.next.next == null) {
            return true;
        }
        //到这时，链表的长度为3
        ListNode slow = head;
        ListNode cur = head.next;
        while(cur.next != null){

            if(cur.next.val == slow.val){
                if(cur.next.next != null) {
                    return false;
                }//避免1011 第三个出现和第一个相同的，但是还有第四个的情况
                cur.next = null;
                slow = slow.next;
                cur = slow.next;
                if (cur == null || slow.val == cur.val) {
                    return true ;
                }
            }else{
                cur = cur.next;
            }
        }
        return false;
    }

}
